
package com.martin.ads.omoshiroilib.ui;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseActivity;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.UploadPhotoResultBean;
import com.imageim.yimirror.common.data.CommonData;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.NetUtil;
import com.imageim.yimirror.common.network.ThreadPoolManager;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.network.listener.NetCallback;
import com.imageim.yimirror.common.network.tool.ParamCreator;
import com.imageim.yimirror.common.ui.ScanView;
import com.imageim.yimirror.common.ui.SceneManager;
import com.imageim.yimirror.common.ui.tip.TipUtil;
import com.imageim.yimirror.common.util.PictureUtils;
import com.imageim.yimirror.common.util.SoundUtil;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.ui.activity.GenderTipActivity;
import com.imageim.yimirror.ui.activity.NoNetworkUploadPhotoActivity;
import com.martin.ads.omoshiroilib.util.BitmapUtils;
import com.nineoldandroids.animation.ObjectAnimator;

import org.apache.http.message.BasicNameValuePair;
import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class DecorateActivity extends BaseActivity implements View.OnClickListener {
    public static final String SAVED_MEDIA_FILE = "saved_media_file";
    private String filePath;
    private ImageView imagePreview;
    private Bitmap bitmap;
    private ScanView scanView;
    private View btnBack;
    private View btnOk;
    private View tvTipRecognizing;
    private boolean isUploading = false;
    //    private Rect rect;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        playAudio();
    }

    private void init() {
        imagePreview = findViewById(R.id.img_preview);
        filePath = getIntent().getStringExtra(SAVED_MEDIA_FILE);

        //        bitmap = PictureUtils.getImage(PictureUtils.compressAndReturnPath(filePath, 85));
        bitmap = PictureUtils.getImage(filePath);
        //        bitmap = PictureUtils.rotateBitmap(270, bitmap);
        //        int bw = bitmap.getWidth();
        //        int bh = bitmap.getHeight();
        //        int left = (int) ((bw - bh * CameraPreviewActivity.preferedRatio) / 2);
        //        int top = 0;
        //        int redPacketHeight = bh;
        //        int redPacketWidth = (int) (redPacketHeight * CameraPreviewActivity.preferedRatio);
        //        rect = new Rect(left, top, left + redPacketWidth, top + redPacketHeight);
        //        bitmap = BitmapUtils.clipBitmap(bitmap, rect);
        imagePreview.setImageBitmap(bitmap);
        // ----------------------------------------------------
        btnBack = findViewById(R.id.btn_back);
        btnOk = findViewById(R.id.btn_ok);
        btnOk.setEnabled(false);
        btnOk.setClickable(false);
        btnBack.setOnClickListener(this);
        btnOk.setOnClickListener(this);
    }

    private void playAudio() {
        int index = new Random().nextInt(3);
        int resId = R.raw.a002;
        switch (index) {
            case 0:
                resId = R.raw.a002;
                break;
            case 1:
                resId = R.raw.a003;
                break;
            case 2:
                resId = R.raw.a004;
                break;
            default:
        }
        SoundUtil.play(resId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (scanView != null) {
            scanView.destroy();
        }
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void initBundle() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_decorate_picture;
    }

    @Override
    protected void initView() {
        scanView = findViewById(R.id.scan_view);
        tvTipRecognizing = findViewById(R.id.tv_tip_recognizing);
        tvTipRecognizing.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private Timer timer;

    @Override
    protected void onResume() {
        super.onResume();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnOk.setEnabled(true);
                        btnOk.setClickable(true);
                    }
                });
            }
        }, 100);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_ok:
                uploadUserPhoto();
                break;
            case R.id.btn_back:
                goBack();
                break;
            default:
        }
    }

    private void goBack() {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        finish();
        SceneManager.toScene(mContext, CameraPreviewActivity.class, null);
    }

    private String photoStr = null;

    private void uploadUserPhoto() {
        if (!isUploading && bitmap != null) {
            isUploading = true;
            showUploadAnim();
            btnOk.setClickable(false);
            new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void... voids) {
                    if (bitmap != null && photoStr == null) {
                        photoStr = BitmapUtils.bitmapToBase64(bitmap, 90);
                    }
                    UserUtil.setImageForBase64(Constants.SEARCH_IMAGE_FOR_IMAGE, photoStr);
                    return photoStr;
                }

                @Override
                protected void onPostExecute(String photoStr) {
                    upload(photoStr);
                }
            }.executeOnExecutor(ThreadPoolManager.getInstance().getThreadPool());

        } //
    }

    private void upload(final String photoStr) {
        List<BasicNameValuePair> params = new ParamCreator().add("userPhoto", photoStr).build();
        NetUtil.postObject(mContext, NetConstants.URL.UPLOAD_SCAN_USER_PHOTO, params, new NetCallback<UploadPhotoResultBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(UploadPhotoResultBean result) {
                //                hideLoading();
                if (result.getGender() == 2) { // female

                    if (result.getUserId() != null) {
                        UserUtil.setUserId(result.getUserId() + "");
                    }

                    //保存用户使用次数、推荐编号用来获取推荐服装、新老用戶標簽、是否做過體驗報告測試題
                    UserUtil.setUserFlag(result.getFlag());
//                    UserUtil.setRecommenNo(result.getRecommendNo());
//                    UserUtil.setUseNo(result.getUseNo());
//                    UserUtil.setExperienceReportFlag(result.getExperienceReportFlag());

                    //  从风格推荐页面重新测试
//                    if (UserUtil.getAgainIntoStylePage()) {
//                        Bundle data = new Bundle();
//                        data.putInt(Constants.STYLE_TYPE, UserUtil.getStyleType());
//                        SceneManager.toScene(mContext, StyleRecommendActivity.class, data);
//                        UserUtil.setAgainIntoStylePage(false);
//                    } else {
//                        //第一次进入
//                        UserUtil.setStyleType(0);
//                        UserUtil.setAgainIntoStylePage(false);
//                        //进入形象力+界面
//                        //TODO 直接进入形象力+界面
//                        SceneManager.toScene(mContext, ImageManageActivity.class, null);
//                    }

                } else { // male
                    SceneManager.toScene(mContext, GenderTipActivity.class, null);
                }
                isUploading = false;
                hideUploadAnim();
                btnOk.setClickable(true);
                EventBus.getDefault().post(new EventMessage(EventCode.CODE_FINISH, null));
                finish();
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                TipUtil.show(errorMsg + " " + errorCode);
                CommonData.scanUserPhotoStr = photoStr;
                UserUtil.setImageForBase64(Constants.SEARCH_IMAGE_FOR_IMAGE, photoStr);
                isUploading = false;
                SceneManager.toScene(mContext, NoNetworkUploadPhotoActivity.class, null);
                hideUploadAnim();
                finish();
                btnOk.setClickable(true);
            }
        }, UploadPhotoResultBean.class);
    } // upload

    private void showUploadAnim() {
        scanView.start();
        btnOk.setVisibility(View.GONE);
        btnBack.setVisibility(View.GONE);
        tvTipRecognizing.setVisibility(View.VISIBLE);
        ObjectAnimator moveDownAnim = ObjectAnimator.ofFloat(tvTipRecognizing, "translationY", -110, 0);
        moveDownAnim.setDuration(460);
        moveDownAnim.setTarget(tvTipRecognizing);
        moveDownAnim.start();
    }

    private void hideUploadAnim() {
        scanView.stop();
    }

    @Override
    public boolean isSupportSwipeBack() {
        return false;
    }

    @Override
    protected boolean isSupportAutoQuit() {
        return true;
    }

    @Override
    protected long getQuitTimeMillis() {
        return 1000 * 25;
    }
}
